<template>
  <div class="form-single-fragment oppo-add" style="position: relative">
    <router-header title="添加商机"></router-header>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="170px"
      size="mini"
      label-position="right"
    >
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <h4><img src="@/assets/img/icon_oppo.png" /></h4>
          <el-row class="el-form-info">
            <el-col :span="12">
              <el-form-item
                label="商机名称"
                :prop="`oppoName`"
                :rules="rules.oppoName"
              >
                <el-input
                  class="input-item"
                  v-model="ruleForm.oppoName"
                  placeholder="请输入"
                  maxlength="20"
                >
                  <el-button slot="append" @click="handleClickRelation"
                    >关联线索</el-button
                  >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="企业名称"
                :prop="`custName`"
                :rules="rules.custName"
              >
                <el-input
                  class="input-item"
                  v-model="ruleForm.custName"
                  placeholder="请输入"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业联系人" prop="contacts">
                <el-input
                  class="input-item"
                  v-model="ruleForm.contacts"
                  placeholder="请输入"
                  maxlength="8"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="联系电话"
                prop="telephone"
              >
                <el-input
                  class="input-item"
                  v-model="ruleForm.telephone"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业属性" prop="contactProperty">
                <el-select
                  v-model="ruleForm.contactProperty"
                  placeholder="请选择"
                >
                  <el-option label="国有企业" value="国有企业"></el-option>
                  <el-option label="国有控股" value="国有控股"></el-option>
                  <el-option label="外资企业" value="外资企业"></el-option>
                  <el-option label="合资企业" value="合资企业"></el-option>
                  <el-option label="私营企业" value="私营企业"></el-option>
                  <el-option label="事业单位" value="事业单位"></el-option>
                  <el-option
                    label="国家行政机关"
                    value="国家行政机关"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商机所属阶段">
                <el-select v-model="ruleForm.stage" placeholder="请选择">
                  <el-option label="立项前" :value="1"></el-option>
                  <el-option label="待立项" :value="2"></el-option>
                  <el-option label="投标中" :value="3"></el-option>
                  <el-option label="已完成" :value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="商机地区"
                :prop="`oppoDistrictCode`"
                :rules="rules.oppoDistrictCode"
              >
                <el-cascader
                  v-model="ruleForm.oppoDistrictCode"
                  ref="ref_areaCodes"
                  :options="areaCodelist"
                  :props="areaCodeprops"
                  clearable
                  @change="areaCodesChange"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址">
                <el-input
                  class="input-item"
                  v-model="ruleForm.detailedAddress"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="业务类型"
                prop="businessType"
                :rules="rules.businessType"
              >
               <el-cascader
                    v-model="businessType"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="false"
                    clearable
                    @change="handleSelectBusinessType"
                  ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计合同额度">
                <el-input
                  type="number"
                  class="input-item"
                  v-model="ruleForm.contractAmount"
                  placeholder="请输入"
                  maxlength="20"
                  oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}"
                >
                  <el-select v-model="ruleForm.units" slot="append" placeholder="请选择" style="width: 130px; padding: 0px 20px; margin: -5px -50px;">
                    <el-option
                      v-for="item in unitsList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label">
                    </el-option>
                  </el-select>
                  <!-- <el-button slot="prepend" icon="el-icon-search"></el-button> -->
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计成交时间">
                <el-date-picker
                  v-model="ruleForm.tradingDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="商机来源"
                :prop="`oppoSource`"
                :rules="rules.oppoSource"
              >
                <el-select v-model="ruleForm.oppoSource" placeholder="请选择">
                  <el-option label="电话来访" value="电话来访"></el-option>
                  <el-option label="客户介绍" value="客户介绍"></el-option>
                  <el-option label="独立开发" value="独立开发"></el-option>
                  <el-option
                    label="社会公开信息"
                    value="社会公开信息"
                  ></el-option>
                  <el-option label="其它" value="其它"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="采购方式"
                prop="procurement"
                v-if="(ruleForm.businessType).indexOf('1475374544690778114') != '-1' || (ruleForm.businessType).indexOf('1475382979209629697') != '-1' || (ruleForm.businessType).indexOf('1475383014387257346') != '-1' ||(ruleForm.businessType).indexOf('1475383048633749506') != '-1'"
              >
              <!-- v-if="businessCode == 'ZB'" -->
              <!-- @change="selectProcurementMode" -->
                <el-select
                  ref="selectProcurement"
                  v-model="ruleForm.procurement"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in procurementList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商机概况" prop="businessProfile">
                <el-input
                  type="textarea"
                  rows="4"
                  class="input-item"
                  v-model="ruleForm.businessProfile"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0">
              <el-button @click="resetForm">取消</el-button>
              <el-button type="primary" @click="submitForm()">确定</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog title="关联线索" :visible.sync="clueDialog">
      <!-- :model="ruleForm" ref="ruleForm" -->
      <el-form
        :line="true"
        label-position="right"
        :model="formInline"
        label-width="80px"
      >
        <el-col :span="10">
          <el-form-item label="线索名称">
            <el-input
              v-model="formInline.clueName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="企业名称">
            <el-input
              v-model="formInline.customerName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="onSubmit"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        :data="tableData"
        size="mini"
        style="width: 100%"
        header-cell-class-name="table-header-gray"
        v-loading="isShowloading"
      >
        <el-table-column
          type="index"
          align="center"
          width="55"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="clueName"
          align="center"
          label="线索名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="businessTypeName"
          align="center"
          label="业务类型"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="customerName"
          align="center"
          label="企业名称"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="contacts"
          align="center"
          label="企业联系人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="telephone"
          align="center"
          label="联系电话"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="clueStatus"
          align="center"
          label="线索状态"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-for="(item, indexs) in clueStatuslist" :key="indexs">
              {{ item.value == scope.row.clueStatus ? item.name : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="clueSource"
          align="center"
          label="线索来源"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createUserName"
          align="center"
          label="创建人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="80">
          <template slot-scope="{ row }">
            <el-button type="primary" @click="handleChooseClue(row)" size="mini"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 10px">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-size="page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next, sizes"
          :total="total"
        ></el-pagination>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { BusinessOpportunities, Cluemanagement } from '@/api/commercial.js';
import { Businesstype } from '@/api/business.js';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
import { mapGetters, mapMutations } from 'vuex';
export default {
  name: 'Opportunitiesadd',
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('联系电话不能为空'));
      } else if (!/^(\d{1,4})-(\d{6,8})$/.test(value) && !/^1\d{10}$/.test(value)) {
        callback(new Error('联系电话格式不正确'));
      } else {
        callback();
      }
    };
    return {
      unitsList: [
        {value: '0', label: '元'},
        {value: '1', label: '万元'},
        {value: '2', label: '亿元'}
      ],
      procurementList: [
        {value: '0', label: '公开招标'},
        {value: '1', label: '邀请招标'},
        {value: '2', label: '竞争性磋商'},
        {value: '3', label: '竞争性谈判'},
        {value: '4', label: '询价'},
        {value: '5', label: '单一来源'},
        {value: '6', label: '进口产品采购'},
        {value: '7', label: '比选'}
      ],
      formInline: {
        clueName: null,
        customerName: null
      },
      businessCode: '',
      loading: false,
      isShowloading: false,
      areaCodelist: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      clueStatuslist: [
        { name: '全部', value: '' },
        { name: '待立项', value: '0' },
        { name: '已完成', value: '1' },
        { name: '已终止', value: '2' }
      ],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false,
        multiple: true
      },
      businesstypeTree: [],
      ruleForm: {
        custName: '',
        contacts: '',
        telephone: '',
        contactProperty: '',
        clueId: undefined,
        procurement: '', // 采购方式
        oppoName: '',
        businessType: '',
        oppoDistrictCode: '',
        stage: '',
        oppoSource: '',
        contractAmount: '',
        tradingDate: '',
        units: ''
      },
      rules: {
        custName: [{ required: true, message: '请输入', trigger: 'blur' }],
        oppoName: [{ required: true, message: '请输入', trigger: 'blur' }],
        businessType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        oppoSource: [{ required: true, message: '请选择', trigger: 'blur' }],
        oppoDistrictCode: [
          { required: false, message: '请选择', trigger: 'blur' }
        ],
        stage: [{ required: true, message: '请选择', trigger: 'blur' }],
        contractAmount: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        contacts: [{ required: true, message: '请输入', trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur'}]
      },
      businessType: [],
      clueDialog: false,
      page_size: 10,
      pageNo: 1,
      tableData: [],
      total: 0
    };
  },
  created () {
    this.ruleForm.units = this.unitsList[0].label;
  },
  computed: {},
  mounted () {
    this.loadbusinesstypeTree();
    this.loadareaCodelistDict();
    if (this.$route.query.clueId) {
      this.loadCluedetail();
    }
    if (this.$route.query.oppoId) {
      this.loadOpportunitiesdetail();
    }
  },
  methods: {
    ...mapMutations([
      'setClientHeight',
      'setClientWidth',
      'setCurrentColumnId',
      'clearCachePage',
      'clearAllTags',
      'setUserInfo',
      'clearOnlineFormCache',
      'setMenuList',
      'setCurrentMenuId'
    ]),
    ...mapGetters([
      'getTagList',
      'getMenuList'
    ]),
    // 线索弹窗
    handleClickRelation () {
      this.loadClueWidgetData();
      this.clueDialog = true;
    },
    // 业务类型
    handleSelectBusinessType (val) {
      this.ruleForm.businessType = val.join(',');
      console.log(val.join(','));
      console.log(val, 440)
    },
    // 关联线索
    handleChooseClue (row) {
      console.log(row);
      // 商机名称
      this.ruleForm.oppoName = row.clueName;
      // 企业名称
      this.ruleForm.custName = row.customerName;
      // 企业联系人
      this.ruleForm.contacts = row.contacts;
      // 联系电话
      this.ruleForm.telephone = row.telephone;
      // 企业属性
      this.ruleForm.contactProperty = row.productIntention;
      // 商机地区
      this.ruleForm.oppoDistrictCode = row.districtCode;
      // 详细地址
      this.ruleForm.detailedAddress = row.detailedAddress;
      // 商机来源
      this.ruleForm.oppoSource = row.clueSource;
      // 业务类型
      this.businessType = row.businessType?.split(',');
      console.log(this.businessType, '-------------');
      this.ruleForm.businessType = row.businessType;
      // 线索Id
      this.ruleForm.clueId = row.id;
      this.clueDialog = false
    },
    // 分页
    handleSizeChange (val) {
      this.page_size = val;
      this.loadClueWidgetData();
    },
    handleCurrentChange (val) {
      this.pageNo = val;
      this.loadClueWidgetData();
    },
    /**
     * 线索列表
     */
    loadClueWidgetData () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo,
        isClueBinding: 20
      };
      return new Promise((resolve, reject) => {
        Cluemanagement.list(this, params)
          .then((res) => {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    // 关联线索搜索
    onSubmit () {
      this.pageNo = 1;
      this.loadClueWidgetData();
    },
    /**
     * 商机详情
     */
    loadOpportunitiesdetail () {
      let params = this.$route.query.oppoId;
      return new Promise((resolve, reject) => {
        BusinessOpportunities.detail(this, params)
          .then((res) => {
            this.businessType = res.data.businessType?.split(',');
            res.data.oppoDistrictCode = Number(res.data.oppoDistrictCode);
            this.ruleForm = res.data;
            console.log(this.ruleForm, 509)
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 线索详情
     */
    loadCluedetail () {
      let params = this.$route.query.clueId;
      return new Promise((resolve, reject) => {
        Cluemanagement.detail(this, params)
          .then((res) => {
            console.log('/*/*/*/*/*/*/*/*/*')
            this.handleChooseClue(res.data);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this)
          .then((res) => {
            if (res.success) {
              res.data.forEach((item) => {
                if (item.children) {
                  item.children.forEach(child => {
                    child.children = null
                  })
                }
              });
              this.businesstypeTree = res.data;
              this.businessCode = res.data?.map(item => item.businessCode);
              console.log(this.businesstypeTree, 549)
              console.log(res.data?.map(item => item.businessCode), 551)
            }
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    businessChange () {
      this.$refs['ref_business'].dropDownVisible = false;
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this)
          .then((res) => {
            let areaCodelist = res.data;
            let areaCodelistnew = [];
            areaCodelist.forEach((item, index) => {
              if (!item.parentId) {
                item.children = [];
                areaCodelistnew.push(item);
              }
            });
            areaCodelistnew.forEach((item1, index1) => {
              let info = areaCodelist.find((item2, index2) => {
                return item1.id === item2.parentId;
              });
              if (info) {
                item1.children = [];
                areaCodelist.forEach((item3, index3) => {
                  if (item1.id === item3.parentId) {
                    item1.children.push(item3);
                  }
                });
              } else {
                item1.children = null;
              }
            });
            areaCodelistnew.forEach((item4, index4) => {
              if (item4.children) {
                item4.children.forEach((item5, index5) => {
                  let info2 = areaCodelist.find((item6, index6) => {
                    return item5.id === item6.parentId;
                  });
                  if (info2) {
                    item5.children = [];
                    areaCodelist.forEach((item7, index7) => {
                      if (item5.id === item7.parentId) {
                        item5.children.push(item7);
                      }
                    });
                  } else {
                    item5.children = null;
                  }
                });
              }
            });
            this.areaCodelist = areaCodelistnew;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 选择商机行政区划
     */
    areaCodesChange () {
      this.$refs['ref_areaCodes'].dropDownVisible = false;
    },
    /**
     * 提交表单
     */
    submitForm () {
      console.log(this.ruleForm, 3333);
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          // 添加-新建客户
          let params = this.ruleForm;
          if (params.id) {
            return new Promise((resolve, reject) => {
              BusinessOpportunities.editCustomer(this, params)
                .then((res) => {
                  this.$message({
                    showClose: true,
                    message: '操作成功！',
                    type: 'success'
                  });
                  this.resetForm();
                })
                .catch((e) => {
                  reject(e);
                });
            });
          }
          return new Promise((resolve, reject) => {
            BusinessOpportunities.addCustomer(this, params)
              .then((res) => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                if (this.$route.query.clueId) {
                  let menuList = this.getMenuList()
                  let menuListChildren = []
                  menuList.map(item => {
                    menuListChildren = menuListChildren.concat(item.children)
                  })
                  this.setCurrentMenuId(menuListChildren.find(item => item.formRouterName === 'Opportunities')?.menuId);
                  this.$router.push({
                    path: '/Opportunities'
                  })
                } else {
                  this.resetForm();
                }
              })
              .catch((e) => {
                reject(e);
              });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm () {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
h4 {
  margin-bottom: 0;
}
.table_container {
  margin: 10px 0;
}
.form-single-info {
  display: flex;
  justify-content: center;
  .el-input--mini .el-input__inner {
    height: 30px;
    line-height: 30px;
}
}
.el-form-info {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.el-form-info strong {
  margin: 0 10px;
}

</style>
<style>
.oppo-add .el-input--mini .el-input__inner{
  height: 30px;
  line-height: 30px;
}
</style>
